package com.xiaojian.blog.controller.admin;

import com.github.pagehelper.PageInfo;
import com.xiaojian.blog.controller.BaseController;
import com.xiaojian.blog.model.CommentPO;
import com.xiaojian.blog.model.CommentPOExample;
import com.xiaojian.blog.model.UserPO;
import com.xiaojian.blog.model.VO.RestResponseVO;
import com.xiaojian.blog.service.CommentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * 评论管理控制器
 */
@Controller
@RequestMapping("admin/comments")
public class CommentController extends BaseController {

    private static final Logger LOGGER = LoggerFactory.getLogger(CommentController.class);

    @Resource
    private CommentService commentService;

    @GetMapping(value = "")
    public String index(@RequestParam(value = "page", defaultValue = "1") int page,
                        @RequestParam(value = "limit", defaultValue = "15") int limit,
                        HttpServletRequest request) {
        UserPO user = this.user(request);
        CommentPOExample example = new CommentPOExample();
        example.setOrderByClause("coid desc");

        example.createCriteria().andAuthorIdEqualTo(user.getUid());
        PageInfo<CommentPO> commentsWithPage = commentService.getCommentsWithPage(example, page, limit);
        request.setAttribute("comments", commentsWithPage);
        return "admin/comment_list";
    }

    @PostMapping(value = "status")//评论过审
    @ResponseBody
    public RestResponseVO delete(@RequestParam Integer coid, @RequestParam String status) {
        try {
            CommentPO comment = commentService.getCommentById(coid);
            if (null != comment) {
                comment.setCoid(coid);
                comment.setStatus(status);
                commentService.update(comment);
            }else {
                return RestResponseVO.fail("操作失败");
            }
        }catch(Exception e) {
            String msg = "操作失败";
            return RestResponseVO.fail(msg);
        }
        return RestResponseVO.ok();
    }

    /**
     * 删除一条评论
     */
    @PostMapping(value = "delete")
    @ResponseBody
    public RestResponseVO delete(@RequestParam Integer coid) {
        try {
            CommentPO comment = commentService.getCommentById(coid);
            if (null == comment) {
                return RestResponseVO.fail("不存在该评论");
            }
            commentService.delete(coid, comment.getCid());
        }catch(Exception e) {
            String msg = "评论删除失败";
            LOGGER.error(msg, e);
            return RestResponseVO.fail(msg);
        }
        return RestResponseVO.ok();
    }
}
